package com.wxl.common.wiget

import android.animation.Animator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.wxl.common.R
import com.wxl.common.util.DPUtil
import com.wxl.common.util.ImgLoader
import com.wxl.common.util.Screen

/**
 * create file time : 2021/3/2
 * create user : wxl
 * subscribe :
 */
class TitleSearchBar : RelativeLayout, LifecycleObserver {

    private var animator: ValueAnimator? = null
    private var _width: Int = 0
    private var isStarted: Boolean = false
    private var reAnimator: ValueAnimator? = null

    @SuppressLint("NewApi", "Recycle", "CustomViewStyleable")
    @JvmOverloads
    constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        attrs?.let {
            context.obtainStyledAttributes(attrs, R.styleable.SearchBar).also {
                val hint: String? = it.getString(R.styleable.SearchBar_text_hint)
                val iconSize = it.getDimensionPixelSize(R.styleable.SearchBar_iconSize, 5)
                val textSize = it.getFloat(R.styleable.SearchBar_text_hint_size, 10f)
                val textViewHeight = it.getDimensionPixelSize(
                    R.styleable.SearchBar_text_height,
                    LayoutParams.WRAP_CONTENT
                )
                _width = it.getDimensionPixelSize(R.styleable.SearchBar_dis_width, 0)
                gravity = Gravity.CENTER_VERTICAL
                createSearchBg(hint, textSize, textViewHeight)
                createSearchIcon(iconSize)
            }.recycle()
        }

    }


    private fun createSearchIcon(searchIconSize: Int) {
        val imageView = ImageView(context)
        val params = LayoutParams(searchIconSize, searchIconSize)
        params.addRule(ALIGN_PARENT_RIGHT)
        params.addRule(CENTER_VERTICAL)
        params.rightMargin = DPUtil.dip2px(5)
        imageView.layoutParams = params
        //ImgLoader.loadResouce(imageView, R.mipmap.icon_search)
        addView(imageView)
    }

    private fun createSearchBg(hint: String?, hintSize: Float, textViewHeight: Int) {
        val textView = TextView(context)
        textView.text = hint
        textView.textSize = hintSize
        val params = LayoutParams(0, textViewHeight)
        params.addRule(ALIGN_PARENT_RIGHT)
        params.addRule(CENTER_VERTICAL)
        textView.layoutParams = params
        textView.setLines(1)
        textView.setTextColor(ContextCompat.getColor(context, R.color.text_drak_gray_color))
        textView.setBackgroundResource(R.drawable.bg_search)
        textView.gravity = Gravity.CENTER
        addView(textView)
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        if (context is AppCompatActivity) {
            (context as AppCompatActivity).lifecycle.addObserver(this)
        }
    }

    fun start() {
        takeIf { childCount > 0 && !isStarted }?.let {
            startAnim()
        }
    }

    fun reStore() {
        takeIf { childCount > 0 && isStarted }?.let {
            reStartAnim()
        }
    }


    private fun reStartAnim() {
        val view = getChildAt(0)
        takeIf { reAnimator == null }?.let {
            reAnimator = ValueAnimator.ofInt(view.layoutParams.width, 0)
            reAnimator?.addUpdateListener {
                val value: Int = it.animatedValue as Int
                view.layoutParams.width = value
                view.requestLayout()
            }
            reAnimator?.duration = 1000
            reAnimator?.addListener(object : Animator.AnimatorListener {
                override fun onAnimationRepeat(animation: Animator?) {

                }

                override fun onAnimationEnd(animation: Animator?) {
                    view.layoutParams.width = 0
                    view.requestLayout()
                    isStarted = false
                }

                override fun onAnimationCancel(animation: Animator?) {
                    view.layoutParams.width = 0
                    view.requestLayout()
                    isStarted = false
                }

                override fun onAnimationStart(animation: Animator?) {

                }
            })
        }
        reAnimator?.start()
    }


    private fun startAnim() {
        isStarted = true
        val view = getChildAt(0)
        takeIf { animator == null }?.let {
            val width = Screen.getWidth(context)
            val moveWidth = width - _width
            val view1 = getChildAt(1)
            val startX = view1.layoutParams.width + DPUtil.dip2px(5)
            animator = ValueAnimator.ofInt(startX, moveWidth)
            animator?.addUpdateListener {
                val value: Int = it.animatedValue as Int
                view.layoutParams.width = value
                view.requestLayout()
            }
            animator?.duration = 1000
        }
        animator?.start()
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        if (context is AppCompatActivity) {
            (context as AppCompatActivity).lifecycle.removeObserver(this)
        }
        animator?.let {
            it.removeAllUpdateListeners()
            it.cancel()
        }
        reAnimator?.let {
            it.removeAllUpdateListeners()
            it.cancel()
        }
    }

}